package com.justreading.netty.protobuftcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.util.UUID;

/**
 * @author LYJ
 * @Description
 * @date 2021 年 11 月 09 日 下午7:38
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {

        //将 buffer 转成字符串
        String message = new String(msg.getContent(), Charset.forName("utf-8"));
        System.out.println("服务器接收到数据 " + message);
        System.out.println("服务器接收到消息量=" + (++this.count));

//服务器回送数据给客户端, 回送一个随机 id ,
        String toString = UUID.randomUUID().toString();
        byte[] bytes = toString.getBytes(CharsetUtil.UTF_8);
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setContent(bytes);
        messageProtocol.setLen(bytes.length);
        ctx.writeAndFlush(messageProtocol);
    }
}
